//
// Created by v on 24-5-13.
//

#include <sys/prctl.h>
#include <unistd.h>

#include "utils/rt_print.h"
#include "utils/cm_utils.h"
#include "cm_discovery_service.h"

CMDiscoveryService::CMDiscoveryService() {
    exited = false;
    protocolConvertInterface = new CMProtocolConvertImplGeneral();
}
CMDiscoveryService::~CMDiscoveryService()
{
    if (protocolConvertInterface)
    {
        delete protocolConvertInterface;
    }
}

int CMDiscoveryService::start(int port, int rport) {
    broadcastFunctionSend.start(port);
    broadcastFunctionRecv.start(rport, true);
    return 0;
}

int CMDiscoveryService::stop() {
    exited = true;
    broadcastFunctionSend.stop();
    broadcastFunctionRecv.stop();
    return 0;
}

int CMDiscoveryService::run() {
    prctl(PR_SET_NAME, "Discovery");
    rtdebug("start");
    std::string data;
    CMDeviceBroadInfo deviceBroadInfo;
    cm_strncpy(deviceBroadInfo.id, "clientit", sizeof(deviceBroadInfo.id));
    cm_strncpy(deviceBroadInfo.name, broadcastFunctionSend.getName().c_str(), sizeof(deviceBroadInfo.name));
    data = protocolConvertInterface->GenerateDeviceBroadInfo(deviceBroadInfo);

    std::string recvData;
    int recvcount = 0;
    while (!exited)
    {
        broadcastFunctionSend.sendBroadcast(data);
        broadcastFunctionSend.recvBroadcast(recvData);
//        broadcastFunctionRecv.recvBroadcast(recvData);
        if (!recvData.empty())
        {
            rtinfo("recv data [%s] count [%d]", recvData.c_str(), recvcount++);
        }

        usleep(500000);
    }
    rtdebug("stop");
    return 0;
}

bool CMDiscoveryService::runDone() { return exited; }
